<template>
    <div class="page">
        <el-row :gutter="20">
            <el-col :span="24" :xs="24" :sm="24" :lg="24">
                <div class="grid-content bg-purple">
                    <div class="panel">
                        <div class="panel-body">
                            <el-row :gutter="20">
                                <el-col :span="4">
                                    <h5>网点管理</h5>
                                </el-col>
                                <el-col :span="6" :offset="13" style="text-align: right;">
                                    <el-button size="medium" type="warning" style="background: rgba(248,154,55,1);" @click="openCreateDialog()">开设网点</el-button>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="24" :xs="24" :sm="24" :lg="24">
                <div class="grid-content bg-purple">
                    <div class="panel">
                        <div class="panel-body">
                            <el-row :gutter="20">
                                <el-col :span="24" :xs="24" :sm="24" :lg="24">
                                    <el-table :data="pointData.data" style="width: 100%" v-loading="listLoading" @row-click="rowClick">
                                        <el-table-column
                                            prop="designation"
                                            label="网点名称">
                                        </el-table-column>
                                        <el-table-column
                                            prop="express.express_name"
                                            label="快递公司">
                                        </el-table-column>
                                        <el-table-column
                                            label="运营状态">
                                            <template slot-scope="scope">{{status[scope.row.status] }}</template>
                                        </el-table-column>
                                        <el-table-column
                                            prop="address"
                                            label="网点地址">
                                        </el-table-column>
                                        <el-table-column
                                            prop="services_count"
                                            label="关联站点">
                                        </el-table-column>
                                        <el-table-column
                                            prop="arrears_money"
                                            label="总欠款（元）">
                                        </el-table-column>
                                        <el-table-column
                                            prop="settlement_money"
                                            label="历史结算（元）">
                                        </el-table-column>
                                        <el-table-column
                                            prop="delivery_sum"
                                            label="历史入库（件）">
                                        </el-table-column>
                                        <el-table-column
                                            prop="send_sum"
                                            label="历史签收（件）">
                                        </el-table-column>
                                    </el-table>
                                </el-col>
                            </el-row>
                        </div>
                        <div class="panel-footer text-right">
                            <el-pagination @size-change="sizeChange" @current-change="currentChange"
                                           :current-page="queryParams.page"
                                           :page-sizes="[5, 10, 20, 50]"
                                           :page-size="queryParams.paginate"
                                           layout="total, sizes, prev, pager, next, jumper"
                                           :total="pointData.total">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>
        <!--新增网点对话框-->
        <el-dialog title="开设网点" :visible.sync="createDialog" width="40%" :before-close="handleCreateClose">
            <el-form ref="addForm" :rules="createRule" :model="createParams" label-width="80px">
                <el-form-item label="网点名称" prop="designation">
                    <el-input v-model="createParams.designation"></el-input>
                </el-form-item>
                <el-form-item label="快递公司" prop="express_id">
                    <el-select v-model="createParams.express_id"  filterable placeholder="请选择快递公司">
                        <el-option
                            v-for="item in express.data"
                            :key="item.id"
                            :label="item.express_name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="网点地址" prop="address">
                    <el-row type="flex" class="row-bg" justify="space-between">
                        <el-col :span="7">
                            <el-select v-model="createParams.province_id"  filterable placeholder="请选择省份" @change="changeProvince">
                                <el-option
                                    v-for="item in province.data"
                                    :key="item.id"
                                    :label="item.province_name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="7">
                            <el-select v-model="createParams.city_id"  filterable placeholder="请选择城市" @change="changeCity">
                                <el-option
                                    v-for="item in city.data"
                                    :key="item.id"
                                    :label="item.city_name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="7">
                            <el-select v-model="createParams.district_id" filterable placeholder="请选择县/区">
                                <el-option
                                    v-for="item in district.data"
                                    :key="item.id"
                                    :label="item.district_name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item label="" prop="address">
                    <el-input v-model="createParams.address"></el-input>
                </el-form-item>
                <el-form-item label="店长姓名" prop="name">
                    <el-input v-model="createParams.name"></el-input>
                </el-form-item>
                <el-form-item label="店长账号" prop="phone">
                    <el-input v-model="createParams.phone" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password">
                    <el-input type="password" v-model="createParams.password"  minlength="6" maxlength="18"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleCreateClose">取 消</el-button>
                <el-button type="warning" style="background: rgba(248,154,55,1);" @click="createPoint()">确 定</el-button>
            </span>
        </el-dialog>
        <!--编辑网点对话框-->
        <el-dialog  :visible.sync="editDialog" width="35%" :before-close="handleEditClose">
            <span slot="title" class="dialog-header">
                <el-row>
                    <el-col :span="8">
                        <p style="font-size: 24px;">{{editParams.designation}}</p>
                    </el-col>
                    <el-col :span="16" v-if="editBtn">
                        <el-row v-if="editing">
                            <el-col :span="8" :offset="8" ><el-button size="medium" type="warning" style="background: rgba(248,154,55,1);"  @click="editQuery">保存</el-button></el-col>
                            <el-col :span="8" ><el-button size="medium" type="danger"  @click="delQuery">删除</el-button></el-col>
                        </el-row>
                        <el-row v-else>
                            <el-col :span="8" :offset="8"><el-button size="medium" type="warning" style="background: rgba(248,154,55,1);"  @click="enableEdit">编辑</el-button></el-col>
                            <el-col :span="8" ><el-button size="medium" type="danger"  @click="delQuery">删除</el-button></el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="16" v-else>
                        <el-row v-if="linkStation.data.length>0">
                            <el-row v-if="linkEditing">
                                <el-col :span="8" :offset="8" ><el-button type="warning" style="background: rgba(248,154,55,1);"  @click="linkEditQuery">保存</el-button></el-col>
                            </el-row>
                            <el-row v-else>
                                 <el-col :span="8" :offset="8" ><el-button type="warning" style="background: rgba(248,154,55,1);"  @click="linkEnableEdit">编辑</el-button></el-col>
                            </el-row>
                        </el-row>
                    </el-col>
                </el-row>
                <el-row>
                    <el-tabs v-model="tabName" @tab-click="tabClick">
                        <el-tab-pane label="网点信息" name="info">
                            <el-form ref="editForm" :rules="editRule" :model="editParams" label-width="150px">
                                <el-form-item label="网点名称：" prop="designation">
                                    <el-input v-model="editParams.designation" :disabled="!editing"></el-input>
                                </el-form-item>
                                <el-form-item label="快递公司：" prop="express_id">
                                     <el-select v-model="editParams.express_id" :disabled="!editing"  filterable placeholder="请选择快递公司">
                                        <el-option
                                            v-for="item in express.data"
                                            :key="item.id"
                                            :label="item.express_name"
                                            :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="运营状态：" prop="status">
                                     <el-select v-model="editParams.status" :disabled="!editing"  filterable placeholder="请选择运营状态">
                                        <el-option
                                            v-for="(item,index) in status"
                                            :key="index"
                                            :label="item"
                                            :value="index">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="网点地址：" prop="address">
                                    <el-row type="flex" class="row-bg" justify="space-between">
                                        <el-col :span="7">
                                            <el-select v-model="editParams.province_id" :disabled="!editing" filterable placeholder="请选择省份" @change="changeProvince">
                                                <el-option
                                                    v-for="item in province.data"
                                                    :key="item.id"
                                                    :label="item.province_name"
                                                    :value="item.id">
                                                </el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="7">
                                            <el-select v-model="editParams.city_id" :disabled="!editing" filterable placeholder="请选择城市" @change="changeCity">
                                                <el-option
                                                    v-for="item in city.data"
                                                    :key="item.id"
                                                    :label="item.city_name"
                                                    :value="item.id">
                                                </el-option>
                                            </el-select>
                                        </el-col>
                                        <el-col :span="7">
                                            <el-select v-model="editParams.district_id" :disabled="!editing" filterable placeholder="请选择县/区">
                                                <el-option
                                                    v-for="item in district.data"
                                                    :key="item.id"
                                                    :label="item.district_name"
                                                    :value="item.id">
                                                </el-option>
                                            </el-select>
                                        </el-col>
                                    </el-row>
                                </el-form-item>
                                <el-form-item label=""  prop="address">
                                    <el-input :disabled="!editing" v-model="editParams.address"></el-input>
                                </el-form-item>
                                <el-form-item label="店长姓名：" prop="name">
                                    <el-input v-model="editParams.name" :disabled="!editing"></el-input>
                                </el-form-item>
                                <el-form-item label="店长手机号：" prop="phone">
                                    <el-input v-model="editParams.phone" :disabled="!editing" maxlength="11"></el-input>
                                </el-form-item>
                                <el-form-item label="创建时间：">
                                    <p>{{editParams.created_at}}</p>
                                </el-form-item>
                                <el-form-item label="总欠款（元）：">
                                    <p>{{editParams.arrears_money}}</p>
                                </el-form-item>
                                <el-form-item label="历史结算（元）：">
                                    <p>{{editParams.settlement_money}}</p>
                                </el-form-item>
                                <el-form-item label="历史入库（件）：">
                                    <p>{{editParams.delivery_sum}}</p>
                                </el-form-item>
                                <el-form-item label="历史签收（件）：">
                                    <p>{{editParams.send_sum}}</p>
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="关联站点" name="link">
                            <div style="min-height: 300px">
                                <el-tabs tab-position="left" @tab-click="linkTabClick" v-model="linkTabName">
                                    <el-tab-pane :label="val.services.designation" v-for="(val,key) in linkStation.data" :key="key" :name="val.stringId">
                                        <el-form ref="linkStationEditForm" :rules="linkStationEditRule" :model="linkEditParams" label-width="120px" v-if="key==linkTabIndex">
                                            <el-form-item label="地址：">
                                                 <p>{{val.services.address}}</p>
                                            </el-form-item>
                                            <el-form-item label="店长：">
                                                 <p>{{val.services.name}} {{val.services.phone}}</p>
                                            </el-form-item>
                                            <el-form-item label="单价（元/件）" prop="unit_price">
                                                <el-input v-model="linkEditParams.unit_price" :disabled="!linkEditing"></el-input>
                                            </el-form-item>
                                             <el-form-item label="信用额度（元）" prop="credit">
                                                <el-input v-model="linkEditParams.credit" :disabled="!linkEditing"></el-input>
                                            </el-form-item>
                                        </el-form>
                                    </el-tab-pane>
                                </el-tabs>
                            </div>
                            <el-pagination @size-change="linkSizeChange" @current-change="linkCurrentChange"
                                           :current-page="queryLinkStationParams.page"
                                           :page-sizes="[5, 10, 20, 50]"
                                           :page-size="queryLinkStationParams.paginate"
                                           layout="total, sizes, prev, pager, next, jumper"
                                           :total="linkStation.total">
                            </el-pagination>
                        </el-tab-pane>
                    </el-tabs>
                </el-row>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import api from '../apis'
    import Vue from 'vue';
    export default {
        name: "Point",
        data(){
            let checkMobile = (rule, value, callback) => {
                let phone=/^[1][3,4,5,7,8][0-9]{9}$/;
                if (!phone.test(value)) {
                    callback(new Error('请输入正确的手机号'));
                } else {
                    callback();
                }
            };
            return{
                //标记是否已经获取当前网点关联站点数据
                linkLoad:false,
                //列表加载开关
                listLoading:false,
                //新增对话框开关
                createDialog:false,
                //编辑对话框开关
                editDialog:false,
                //编辑对话框按钮显示隐藏状态
                editBtn:true,
                //是否开启修改
                editing:false,
                //编辑对话框默认标签页
                tabName: 'info',
                //关联站点默认标签页
                linkTabName:'',
                //关联站点标签页下标
                linkTabIndex:0,
                //会员列表数据
                pointData:{
                    data: [],
                    total: 0,
                },
                //日志数据
                logData:{
                    data:[],
                    total:0,
                },
                //日志请求参数
                queryLogParams:{
                    page:1,
                    paginate:5,
                    type:1,
                    uid:'',
                },
                //列表请求参数
                queryParams: {
                    page: 1,
                    paginate: 10,
                },
                //关联站点请求参数
                queryLinkStationParams:{
                    network_id:'',
                    page:1,
                    paginate:5,
                },
                //新增请求参数
                createParams:{

                },
                //新增验证规则
                createRule:{
                    phone: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        {validator: checkMobile, trigger: 'blur'},
                    ],
                    name: [
                        { required: true, message: '请输入店长姓名', trigger: 'blur' },
                    ],
                    address: [
                        { required: true, message: '请输入地址', trigger: 'blur' },
                    ],
                    designation:[
                        { required: true, message: '请输入网点名称', trigger: 'blur' },
                    ],
                    password:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                    ],
                    express_id:[
                        { required: true, message: '请选择快递公司', trigger: 'blur' },
                    ],
                },
                //修改请求参数
                editParams:{

                },
                //修改验证规则
                editRule:{
                    phone: [
                        { required: true, message: '请输入手机号码', trigger: 'blur' },
                        {validator: checkMobile, trigger: 'blur'}
                    ],
                    name: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                    ],
                    designation:[
                        { required: true, message: '请输入网点名称', trigger: 'blur' },
                    ],
                    express_id:[
                        { required: true, message: '请选择快递公司', trigger: 'blur' },
                    ],
                    status:[
                        { required: true, message: '请选择运营状态', trigger: 'blur' },
                    ],
                    address:[
                        { required: true, message: '请输入地址', trigger: 'blur' },
                    ],

                },
                //关联站点修改验证规则
                linkStationEditRule:{
                    unit_price:[
                        { required: true, message: '请选择运营状态', trigger: 'blur' },
                    ],
                    credit:[
                        { required: true, message: '请选择运营状态', trigger: 'blur' },
                    ],
                },
                //修改对话框数据
                editData:{

                },
                //状态数组
                status:[
                    '申请开通',
                    '运营中',
                    '已停业'
                ],
                //省份数据
                province:{
                    data:[

                    ],
                },
                //城市数据
                city:{
                    data:[

                    ],
                },
                //区县数据
                district:{
                    data:[

                    ],
                },
                //快递公司数据
                express:{
                    data:[],
                },
                //关联站点数据
                linkStation:{
                    data:[],
                    total:0,
                },
                //关联站点编辑状态数组
                linkEditing:false,
                //关联站点修改数据
                linkEditParams:{
                    id:'',
                    unit_price:'',
                    credit:'',
                }
            }
        },
        methods:{
            /**
             * 请求快递公司列表
             */
            queryExpress()
            {
                api.common.fetchExpress().then(response=>{
                    this.express = response.data;
                }).catch(errors=>{

                })
            },
            /**
             * 请求省份数据
             */
            queryProvince()
            {
                api.common.fetchProvince().then(response=>{
                    this.province = response.data;
                }).catch(errors=>{

                })
            },
            /**
             * 请求城市数据
             */
            queryCity(Province='')
            {
                api.common.fetchCity({province_id:Province}).then(response=>{
                    this.city = response.data;
                    this.createParams.city_id = this.city.data[0].id;
                    this.editParams.city_id = this.city.data[0].id;
                    this.queryDistrict(this.city.data[0].id);
                }).catch(errors=>{

                })
            },
            /**
             * 请求区县数据
             */
            queryDistrict(City='')
            {
                api.common.fetchDistrict({city_id:City}).then(response=>{
                    this.district = response.data;
                    Vue.set(this.createParams,'district_id',this.district.data[0].id);
                    Vue.set(this.editParams,'district_id',this.district.data[0].id);
                }).catch(errors=>{

                })
            },
            /**
             * 请求网点列表
             */
            queryPoint(){
                this.listLoading = true;
                api.point.fetch(this.queryParams).then(response=>{
                    this.pointData = response.data;
                    this.listLoading = false;
                }).catch(errors=>{
                    this.$message.error('请求失败');
                })
            },
            /**
             * 根据id获取详情
             */
            fetchById(id){
                api.point.fetchById(id).then(response=>{
                    this.editParams = response.data.data;
                    this.queryCity(this.editParams.province_id);
                    this.queryDistrict(this.editParams.city_id);
                }).catch(errors=>{
                    this.$message.error('请求失败');
                })
            },
            /**
             * 打开新增对话框
             */
            openCreateDialog()
            {
                this.createParams = {}
                this.createDialog = true;
            },
            /**
             * 列表行选中
             * @param row
             * @param event
             * @param column
             */
            rowClick(row, event, column){
                this.fetchById(row.id);
                this.queryLinkStationParams.network_id = row.id;
                this.editParams.id = row.id;
                this.editDialog = true;
            },
            /**
             * 改变每页数量的时候请求列表
             * @param size
             */
            sizeChange(size){
                this.queryParams.paginate = size;
                this.queryPoint();
            },
            /**
             * 改变当前页的时候请求列表
             * @param index
             */
            currentChange(index){
                this.queryParams.page = index;
                this.queryPoint();
            },
            /**
             * 跳转到最后一页
             */
            jumpToLastPage () {
                let last = Math.ceil(this.pointData.total / this.queryParams.paginate);
                if (this.queryParams.page < last) {
                    this.queryParams.page = last;
                }
                this.queryPoint();
            },
            /**
             * 修改对话框点击删除按钮
             */
            delQuery(){
                this.$confirm('确认删除网点？', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    api.point.destroy(this.editParams.id).then(response=>{
                        this.editDialog = false;
                        this.queryPoint();
                    }).catch(errors=>{
                        this.$message.error(errors.response.data.resultMessage);
                    });
                }).catch(() => {

                });
            },
            /**
             * 修改对话框点击保存按钮
             */
            editQuery(){
                this.$refs['editForm'].validate((valid) =>{
                    if(valid){
                        api.point.update(this.editParams.id,this.editParams).then(response=>{
                            for (let i in this.pointData.data){
                                if(this.pointData.data[i].id==this.editParams.id){
                                    Vue.set(this.pointData.data, i, response.data.data);
                                    break;
                                }
                            }
                            this.editing = false;
                            // this.handleEditClose();
                            this.$message.success('修改成功');
                        }).catch(errors=>{
                            this.$message.error(errors.response.data.resultMessage);
                        });
                    }else{
                        return false;
                    }
                });
            },
            /**
             *
             */
            linkEditQuery(){
                api.point.updateLinkStation(this.linkEditParams).then(response=>{
                    for(let i in this.linkStation.data){
                        if(this.linkStation.data[i].id==response.data.data.id){
                            Vue.set(this.linkStation.data[i],'credit',response.data.data.credit);
                            Vue.set(this.linkStation.data[i],'unit_price',response.data.data.unit_price);
                            break;
                        }
                    };
                    this.linkEditing = false;
                    this.$message.success('修改成功');
                }).catch(errors=>{
                    this.$message.error('请求失败');
                })
            },
            /**
             * 关闭新增对话框
             */
            handleCreateClose(){
                this.createParams = {

                };
                this.createDialog = false;
                this.$refs['addForm'].resetFields();
                this.linkTabIndex = 0;
            },
            /**
             * 关闭修改对话框
             */
            handleEditClose(){
                this.editDialog = false;
                this.editData = {

                };
                this.editing = false;
                this.linkLoad = false;
                this.editBtn = true;
                this.tabName = 'info';
                this.linkStation = {
                    data:[],
                    total:0,
                };
                this.city = {
                    data:[],
                };
                this.district = {
                    data:[],
                }
                this.$refs['editForm'].resetFields();
            },
            /**
             * 编辑对话框标签页切换
             */
            tabClick(tab, event){
                if(tab.name=='info'){
                    this.editBtn = true;
                }else{
                    this.editBtn = false;
                    if(!this.linkLoad){
                        this.queryLinkStation();
                        this.linkLoad = true;
                    }
                }
            },
            /**
             * 关联站点标签页切换
             */
            linkTabClick(tab,event){
                this.linkTabName = tab.name;
                this.linkTabIndex = tab.index;
                this.linkEditParams.id = this.linkStation.data[tab.index].id;
                this.linkEditParams.credit = this.linkStation.data[tab.index].credit;
                this.linkEditParams.unit_price = this.linkStation.data[tab.index].unit_price;
                this.linkEditing = false;
            },
            /**
             * 修改对话框点击修改按钮
             */
            enableEdit(){
                this.editing = true;
            },
            /**
             * 当前查看的关联站点点击修改按钮
             */
            linkEnableEdit(){
                this.linkEditing = true;
            },
            /**
             * 新增网点请求
             */
            createPoint(){
                this.$refs['addForm'].validate((valid) =>{
                    if(valid){
                        api.point.create(this.createParams).then(response=>{
                            this.jumpToLastPage();
                            this.handleCreateClose();
                            this.$message.success('新增成功');
                        }).catch(errors=>{
                            this.$message.error(errors.response.data.resultMessage);
                        });
                    }else{
                        return false;
                    }
                });
            },
            /**
             * 省选择器改变
             */
            changeProvince(val){
                this.queryCity(val);
            },
            /**
             * 市选择器改变
             */
            changeCity(val){
                this.queryDistrict(val);
            },
            /**
             * 获取关联站点数据
             */
            queryLinkStation(){
                api.point.fetchLinkStation(this.queryLinkStationParams).then(response=>{
                    this.linkStation = response.data;
                    if(this.linkStation.data.length>0){
                        this.linkEditParams.id = this.linkStation.data[0].id;
                        this.linkEditParams.credit = this.linkStation.data[0].credit;
                        this.linkEditParams.unit_price = this.linkStation.data[0].unit_price;
                        for (let i in this.linkStation.data){
                            this.linkStation.data[i].stringId = String(this.linkStation.data[i].id);
                        }
                        this.linkTabName = this.linkStation.data[0].stringId;
                    };
                    this.linkTabIndex = 0;
                }).catch(errors=>{
                    this.$message.error('请求失败');
                })
            },
            /**
             * 关联站点分页每页数据量改变
             */
            linkSizeChange(size){
                this.queryLinkStationParams.paginate = size;
                this.queryLinkStation();
            },
            /**
             * 关联站点分页页码改变
             */
            linkCurrentChange(page){
                this.queryLinkStationParams.page = page;
                this.queryLinkStation();
            }

        },
        mounted (){
            this.queryPoint();
            this.queryExpress();
            this.queryProvince();
        }
    }
</script>

<style lang="scss">

</style>
